<template>
  <div>
    <!-- 搜索表单 -->
    <div>
      <el-form :inline="true">
        <el-form-item label="角色名称">
          <el-input v-model="keyword" placeholder="角色名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearchSysRoles">
            搜索
          </el-button>
          <el-button type="info" @click="handleClear">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 添加按钮 -->
    <div>
      <el-button
        type="success"
        @click="handleShowSaveSysRoleDialog"
        size="small"
      >
        添加
      </el-button>
      <hr style="margin-top:-2px;" />
    </div>
    <!-- 展示数据的表格 -->
    <div>
      <el-table :data="sysRoles" stripe style="width: 100%">
        <el-table-column type="index" label="编号" width="80" />
        <el-table-column prop="roleName" label="角色名称" width="180" />
        <el-table-column prop="roleCode" label="角色code" width="180" />
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button
              size="small"
              @click="handleShowUpdateSysRoleDialog(scope.row)"
              type="primary"
            >
              修改
            </el-button>
            <el-button
              @click="handleDelete(scope.row)"
              size="small"
              type="danger"
            >
              删除
            </el-button>
            <el-button
              type="warning"
              size="small"
              @click="showAssignMenu(scope.row)"
            >
              分配菜单
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页导航条 -->
    <div>
      <el-pagination
        v-model:current-page="pageNum"
        v-model:page-size="pageSize"
        :page-sizes="[1, 2, 3, 4, 5]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 新增角色对话框 -->
    <div>
      <el-dialog v-model="dialogFormVisible" :title="title">
        <el-form :model="sysRole">
          <el-form-item label="角色名称" label-width="120px">
            <el-input v-model="sysRole.roleName" />
          </el-form-item>
          <el-form-item label="角色Code" label-width="120px">
            <el-input v-model="sysRole.roleCode" />
          </el-form-item>
          <el-form-item label="角色描述" label-width="120px">
            <el-input v-model="sysRole.description" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button
              type="primary"
              :disable="saveSysRoleFlag"
              @click="handleSaveOrUpdateSysRole"
            >
              提交
            </el-button>
          </span>
        </template>
      </el-dialog>
    </div>
    <!-- 给角色分配菜单的对话框 -->
    <div>
      <el-dialog v-model="dialogMenuVisible" title="分配菜单" width="40%">
        <el-form label-width="80px">
          <el-tree
            :data="sysMenuTreeList"
            show-checkbox
            ref="myTree"
            default-expand-all
            node-key="id"
            :props="defaultProps"
            :default-checked-keys="checkedMenuIds"
            :check-on-click-node="true"
          />
          <el-form-item>
            <el-button type="primary" @click="handleAssignMenus">
              提交
            </el-button>
            <el-button @click="dialogMenuVisible = false">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>
<script setup>
import {
  GetSysRolePage,
  DeleteSysRole,
  SaveSysRole,
  GetSysRoleById,
  UpdateSysRole,
} from '@/api/sysrole'
import { GetMenusByRoleId, AssignMenus2Role } from '@/api/sysMenu'
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
/* day07-- 给角色分配菜单 */
//对话框显示隐藏的属性
let dialogMenuVisible = ref(false)
//对话框 树形图 需要的数据列表
let sysMenuTreeList = ref([])
//对话框 树形图 默认选中菜单的id列表
let checkedMenuIds = ref([])
// 分配菜单的角色的id
let roleId = ref(null)
let myTree = ref(null)
//对话框 树形图 解析数据时的配置
const defaultProps = {
  //树形图 级联关系 下一级节点集合的属性名
  children: 'children',
  //树形图 每个节点展示时的标题使用的属性名
  label: 'title',
}
const showAssignMenu = async row => {
  //置空缓存的集合：
  sysMenuTreeList.value = []
  checkedMenuIds.value = []
  roleId.value = row.id
  //查询数据 再显示对话框
  const { data } = await GetMenusByRoleId(row.id)
  //data是一个map：menus   checkedMenuIds
  console.log(data.menus, data.checkedMenuIds)
  sysMenuTreeList.value = data.menus
  checkedMenuIds.value = data.checkedMenuIds
  //显示对话框
  dialogMenuVisible.value = true
}
//提交分配菜单的请求
const handleAssignMenus = async () => {
  //获取选中的菜单id集合    myTree.value用来获取页面中ref值为myTree的dom对象
  console.log(myTree.value.getCheckedKeys())
  await AssignMenus2Role(roleId.value, myTree.value.getCheckedKeys())
  ElMessage.success('分配菜单成功')
  dialogMenuVisible.value = false
}

/* day07-- end */

//分页需要使用的数据
let keyword = ref('')
let pageNum = ref(1)
let pageSize = ref(3)
let total = ref(0)
//角色列表
let sysRoles = ref([])
//新增角色对话框的数据
let dialogFormVisible = ref(false)
let title = ref('新增角色')
let sysRole = ref({
  roleName: '',
  roleCode: '',
  description: '',
})
// 对话框提交按钮禁用状态
let saveSysRoleFlag = ref(false)
//页面渲染后执行
onMounted(() => {
  fetchData()
})

//== 查询分页数据的函数
const fetchData = async () => {
  const { code, message, data } = await GetSysRolePage(
    keyword.value,
    pageNum.value,
    pageSize.value
  )
  if (+code === 200) {
    //data代表分页数据
    console.log(code, message, data)
    //解析data：
    sysRoles.value = data.list
    total.value = data.total
  } else {
    ElMessage.error(message)
  }
}
//分页导航条 事件函数
// === 每页记录条数改变时回调
const handleSizeChange = () => {
  fetchData()
}
// === 页码改变时的回调
const handleCurrentChange = () => {
  fetchData()
}
//条件搜索事件函数
const handleSearchSysRoles = () => {
  //初始化页码和pageSize后再执行条件查询
  pageNum.value = 1
  pageSize.value = 3
  fetchData()
}
//重置条件事件函数
const handleClear = () => {
  pageNum.value = 1
  pageSize.value = 3
  keyword.value = ''
  fetchData()
}
//删除按钮事件函数
const handleDelete = row => {
  console.log(row)
  //弹出删除确认
  ElMessageBox.confirm(`您确认删除角色【${row.roleName}】吗?`, 'Warning', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      //异步请求 删除id对应的角色
      const { code, message } = await DeleteSysRole(row.id)
      if (+code === 200) {
        ElMessage.success(message)
        //刷新页面数据
        fetchData()
      } else {
        ElMessage.error(message)
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}
//显示新增角色对话框按钮事件函数
const handleShowSaveSysRoleDialog = () => {
  sysRole.value = {}
  title.value = '新增角色'
  //显示对话框
  dialogFormVisible.value = true
}
//新增角色对话框提交按钮事件函数
const handleSaveSysRole = async () => {
  //防止表单重复提交
  saveSysRoleFlag.value = true
  const { code, message } = await SaveSysRole(sysRole.value)
  if (+code === 200) {
    ElMessage.success('新增成功')
    //刷新页面的数据
    pageNum.value = 100000
    fetchData()
  } else {
    ElMessage.error(message)
  }
  //关闭对话框
  dialogFormVisible.value = false
  //取消按钮禁用状态
  saveSysRoleFlag.value = false
}
//表格 修改角色按钮弹出更新对话框回显数据事件函数
const handleShowUpdateSysRoleDialog = async row => {
  const { code, message, data } = await GetSysRoleById(row.id)
  if (+code === 200) {
    title.value = '更新角色'
    //对象深拷贝： 将data所有的属性值 拷贝给sysRole对象的属性
    //浅拷贝：
    sysRole.value = data
    //显示对话框
    dialogFormVisible.value = true
  } else {
    ElMessage.error(message)
  }
}
//新增或更新提交按钮事件函数
const handleSaveOrUpdateSysRole = () => {
  if (sysRole.value.id) {
    //提交更新请求
    handleUpdateSysRole()
  } else {
    //提交新增请求
    handleSaveSysRole()
  }
}
//更新角色
const handleUpdateSysRole = async () => {
  //防止表单重复提交
  saveSysRoleFlag.value = true
  const { code, message } = await UpdateSysRole(sysRole.value)
  if (+code === 200) {
    ElMessage.success('更新成功')
    //刷新页面的数据
    // pageNum.value = 100000
    fetchData()
  } else {
    ElMessage.error(message)
  }
  //关闭对话框
  dialogFormVisible.value = false
  //取消按钮禁用状态
  saveSysRoleFlag.value = false
}
</script>
